package sacnner;

import annotation.Bean;
import java.util.Set;

import bean.DefaultBeanDefinition;
import bean.DefaultBeanFactory;
import org.reflections.Reflections;

public class ClassPathBeanDefinitionScanner {
    private final DefaultBeanFactory beanFactory;

    public ClassPathBeanDefinitionScanner(DefaultBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    /**
     * 扫描指定包路径下的Bean
     */
    public void scan(String... basePackages) {
        for (String pkg : basePackages) {
            Reflections reflections = new Reflections(pkg);
            Set<Class<?>> beanClasses = reflections.getTypesAnnotatedWith(Bean.class);

            for (Class<?> clazz : beanClasses) {
                Bean annotation = clazz.getAnnotation(Bean.class);
                String beanName = getBeanName(annotation, clazz);

                DefaultBeanDefinition definition = new DefaultBeanDefinition(clazz);
                definition.setScope(annotation.scope());
                definition.setPrimary(annotation.primary());

                beanFactory.registerBeanDefinition(beanName, definition);
            }
        }
    }

    private String getBeanName(Bean annotation, Class<?> clazz) {
        String name = annotation.value();
        if (!name.isEmpty()) return name;

        // 优先使用接口名称
        Class<?>[] interfaces = clazz.getInterfaces();
        if (interfaces.length > 0) {
            String interfaceName = interfaces[0].getSimpleName();
            return interfaceName.substring(0, 1).toLowerCase() + interfaceName.substring(1);
        }

        // 使用类名作为兜底
        String className = clazz.getSimpleName();
        return className.substring(0, 1).toLowerCase() + className.substring(1);
    }
}
